<?php

namespace app\common\controller;

use app\common\API;
use app\common\JWT;
use think\Controller;
use think\Request;
use think\Db;
use think\Session;
use think\Cookie;
use think\config;
use think\Log;
use think\Cache;

class Base extends Controller
{
    /**
     * 状态码
     */
    const HTTP_STATUS_SUCCESS = 200;    // 操作成功
    const HTTP_STATUS_ERROR = 400;    // 操作失败
    const HTTP_STATUS_NO_PERMISSION = 403;    // 没有权限
    const HTTP_STATUS_NOT_FOUND = 404;    // 404
    const HTTP_STATUS_FAIL = 500;    // 发生错误
    const HTTP_STATUS_NOT_LOGGED = 100;    // 未登录


    protected $WECHAT_CONFIG;
    protected $WECHAT_URL;
    protected $WECHAT_TOKEN_URL;
    protected $WECHAT_MESSAGE_URL;
    protected $WECHAT_TEMPLATE_ORDER;
    protected $WECHAT_TEMPLATE_REMIND;
    protected $WEEKS;

    public function __construct()
    {
        $this->WECHAT_CONFIG = config('WeChat');
        $this->WECHAT_URL = "https://api.weixin.qq.com/sns/jscode2session";
        $this->WECHAT_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
        $this->WECHAT_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=";
        $this->WECHAT_TEMPLATE_ORDER = "kDeUpemjRd1CdfsAGqvzr3W6BLoxOhrwEcZDdTAU4Tw";
        $this->WECHAT_TEMPLATE_REMIND = "b6NUxvfGpVkfZvzKd5uE7yZ-KhOLh2Srw8T2JhQmYDo";

    }


    /**
     * 此AccessToken
     * 获得AccessToken
     * @return mixed
     */
    public function getAccessToken()
    {
        // 获取缓存
        $access = cache('access_token');
        Log::info($access, "accessult");
        $config = $this->WECHAT_CONFIG;

        $url = $this->WECHAT_TOKEN_URL;

        // 缓存不存在-重新创建
        if (empty($access)) {
            // 获取 access token
            $url = $url . "?grant_type=client_credential&appid=" . $config['appId'] . "&secret=" . $config['appSecret'];

            $result = curl_get($url);

            $result = json_decode($result, true);


            // 保存至缓存
            $access = $result['access_token'];

            cache('access_token', $access, 7000);
        }
        return $access;
    }


    /**
     * 生成 Token
     *
     * @param  array $payload 载荷
     * @return string
     */
    protected function createToken(array $payload = [])
    {
        try {
            $config = config('token');
            $payload = array_merge([
                'iss' => $config['issuer'],
                'iat' => $_SERVER['REQUEST_TIME'],
                'exp' => $_SERVER['REQUEST_TIME'] + config('auth.access_token_expired')
            ], $payload);
            return JWT::encode($payload, $config['application_signature_secret']);
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 验证 Token
     *
     * @return payload / false
     */
    protected function authToken()
    {
        try {
            $key = config('token')['application_signature_secret'];

            if (
                ($jwt = $_SERVER['HTTP_AUTHORIZATION'] ? $_SERVER['HTTP_AUTHORIZATION'] : FALSE)
                && ($payload = JWT::decode($jwt, $key))
            ) {
                return $payload;
            }

            return false;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 操作成功
     *
     * @param  string $message 响应信息
     * @param  mixed $data 响应数据
     */
    protected function successful($message = '', $data = null)
    {
        $this->responseJSON(self::HTTP_STATUS_SUCCESS, $message, $data);
    }

    /**
     * 操作失败
     *
     * @param  string $message 响应信息
     * @param  mixed $data 响应数据
     */
    protected function failed($message = '', $data = null)
    {
        $this->responseJSON(self::HTTP_STATUS_ERROR, $message, $data);
    }

    /**
     * 未找到数据
     *
     * @param  string $message 响应信息
     * @param  mixed $data 响应数据
     */
    protected function notFound($message = '未找到相关数据', $data = null)
    {
        $this->responseJSON(self::HTTP_STATUS_NOT_FOUND, $message, $data);
    }

    /**
     * 未登录
     *
     * @param  string $message 响应信息
     * @param  mixed $data 响应数据
     */
    protected function notLogged($message = '未登录', $data = null)
    {
        $this->responseJSON(self::HTTP_STATUS_NOT_LOGGED, $message, $data);
    }


    /**
     * 没有权限
     *
     * @param  string $message 响应信息
     * @param  mixed $data 响应数据
     */
    protected function noAccess($message = '没有权限', $data = null)
    {
        $this->responseJSON(self::HTTP_STATUS_NO_PERMISSION, $message, $data);
    }

    /**
     * 发生错误
     *
     * @param  string $message 响应信息
     * @param  mixed $data 响应数据
     */
    protected function fail($message = '发生错误', $data = null)
    {
        $this->responseJSON(self::HTTP_STATUS_FAIL, $message, $data);
    }


    /**
     * 输出 JSON 响应
     *
     * @param  integer $status 响应状态
     * @param  string $message 响应信息
     * @param  mixed $data 响应数据
     */
    protected function responseJSON($status, $message = '', $data = NULL)
    {
        $response = [
            'status' => $status,
            'message' => $message
        ];

        $data !== NULL && $response['data'] = $data;

        header('Content-type:application/json');
        exit(json_encode($response, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 获取 GET 参数
     *
     * @param  string $name 参数名
     * @param  mixed $default 默认值
     * @return mixed
     */
    protected function get($name = NULL, $default = NULL)
    {
        if (!$name)
            return $_GET;

        return $_GET[$name] ? $_GET[$name] : $default;
    }

    /**
     * 获取 POST 参数
     *
     * @param  string $name 参数名
     * @param  mixed $default 默认值
     * @return mixed
     */
    protected function post($name = NULL, $default = NULL)
    {
        if (!$name)
            return $_POST;

        return $_POST[$name] ? $_POST[$name] : $default;
    }

    /**
     * 是否GET请求
     *
     * @return boolean
     */
    protected function isGet()
    {
        return Request::isGet();
    }

    /**
     * 是否POST请求
     *
     * @return boolean
     */
    protected function isPost()
    {
        return Request::isPost();
    }


}